package com.ddm.controller.wxadmin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ddm.constant.MessageConstant;
import com.ddm.dto.page.PageQueryDTO;
import com.ddm.dto.vxDTO.AnnouncementDTO;
import com.ddm.entity.vxEntity.Announcement;
import com.ddm.entity.vxEntity.Exam;
import com.ddm.entity.vxEntity.ExamQuestion;
import com.ddm.enumeration.AnnouncementType;
import com.ddm.exception.DataErrorException;
import com.ddm.result.PageResult;
import com.ddm.result.Result;
import com.ddm.service.vxService.AnnouncementService;
import com.ddm.utils.BeanCopyUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/announcement")
@Slf4j
@Api("公告接口")
public class AnnouncementController {

    @Autowired
    AnnouncementService announcementService;


    @PostMapping
    @ApiOperation("添加公告")
    public Result<String> addAnnouncement(@RequestBody AnnouncementDTO announcementDTO ){
        log.info("添加公告:{}",announcementDTO.getName());
        if (announcementDTO.getName() ==null || announcementDTO.getContent()==null){
            throw new DataErrorException(MessageConstant.NULL_DATA);
        }
        LambdaQueryWrapper<Announcement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Announcement::getName,announcementDTO.getName()).eq(Announcement::getContent,announcementDTO.getContent());
        Announcement announcement = announcementService.getOne(wrapper);
        if (announcement !=null){
            throw new DataErrorException(MessageConstant.ALREADY_EXISTS);
        }
        announcement = BeanCopyUtil.BeanCopy(announcementDTO, Announcement.class);
        // 转换数字类型为枚举类型
        if (announcementDTO.getType() != null) {
            announcement.setType(getAnnouncementTypeByValue(announcementDTO.getType()));
        }
        announcementService.save(announcement);
        return Result.success();
    }


    @PutMapping("/{id}")
    @ApiOperation("根据id修改公告")
    public Result<String> updateAnnouncement(@RequestBody AnnouncementDTO announcementDTO , @PathVariable Long id){
        log.info("修改公告:{}",announcementDTO.getName());
        if (announcementService.getById(id) == null){
            throw new DataErrorException(MessageConstant.ERROR_DATA);
        }
        Announcement announcement = BeanCopyUtil.BeanCopy(announcementDTO, Announcement.class);
        announcement.setId(id);
        // 转换数字类型为枚举类型
        if (announcementDTO.getType() != null) {
            announcement.setType(getAnnouncementTypeByValue(announcementDTO.getType()));
        }
        announcementService.updateById(announcement);
        return Result.success("修改成功");
    }

    @GetMapping
    @ApiOperation("分页获取公告")
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public Result<PageResult> getAnnouncementList( PageQueryDTO pageQueryDTO){
        log.info("分页获取公告");
        return Result.success(announcementService.getAnnouncementList(pageQueryDTO));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除公告")
    public Result<String> deleteAnnouncement(@PathVariable Long id ){
        log.info("根据id删除公告:{}",id);
        Announcement announcement = announcementService.getById(id);
        if (announcement == null){
            throw new DataErrorException(MessageConstant.ERROR_DATA);
        }
        announcementService.removeById(id);
        return Result.success("删除成功");
    }

    @DeleteMapping("/batch/{ids}")
    @ApiOperation("批量删除公告")
    @Transactional
    public Result  deleteAnnouncementList(@PathVariable List<Long> ids){
        log.info("批量删除公告,IDs:{}",ids);
        if (ids == null){
            throw new DataErrorException(MessageConstant.NULL_DATA);
        }
        List<Announcement> existList = announcementService.listByIds(ids);
        if (ids.size() != existList.size()){
            throw new DataErrorException(MessageConstant.ERROR_DATA);
        }
        announcementService.removeByIds(ids);
        return Result.success("删除成功");
    }

    @GetMapping("/type/{type}")
    @ApiOperation("根据类型分页获取公告")
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public Result<PageResult> getAnnouncementListByType(PageQueryDTO pageQueryDTO, @PathVariable String type){
        log.info("根据类型分页获取公告:{}", type);
        AnnouncementType announcementType;
        try {
            // 先尝试按数字解析
            int typeValue = Integer.parseInt(type);
            announcementType = getAnnouncementTypeByValue(typeValue);
        } catch (NumberFormatException e) {
            // 如果不是数字，尝试按枚举名称解析
            try {
                announcementType = AnnouncementType.valueOf(type.toUpperCase());
            } catch (IllegalArgumentException ex) {
                throw new DataErrorException("无效的公告类型");
            }
        }
        return Result.success(announcementService.getAnnouncementListByType(pageQueryDTO, announcementType));
    }

    private AnnouncementType getAnnouncementTypeByValue(int value) {
        for (AnnouncementType type : AnnouncementType.values()) {
            if (type.getValue() == value) {
                return type;
            }
        }
        throw new DataErrorException("无效的公告类型值");
    }

}
